Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
using fetch with express and ejs gives 400 bad request aswell as unexpected token < in json

Using fetch I'm getting a bad request as well as unexpected token < in JSON both point to search.js which is where I'm making the fetch request I have tried sending via an API client and it is working I'm trying to send the fetch request via input onkeyup. Also noticed my error is uncaught

Fetch req:

const searchResults =  function(e){
fetch('/elpers/search' ,
{
 method: 'POST', 
 headers: {'Content-Type': 'application/json'},
 body: JSON.stringify(e.value)
}).then(res => {
  res.json()
}).then(data => {
 console.log(data)
}).catch(err => {
console.error(err)
})
}

POST route

 const postSearch = (req, res) => {
console.log(req.body)
res.send({'result': 'value'});
}

edit: this worked for me JSON.stringify({result: e.value})

Error:

search.js:2 POST http://localhost:3000/elpers/search 400 (Bad Request) VM118:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to use res.json() instead of res.send() and JSON.stringify(e.value) to JSON.stringify({result: e.value})

about 4 years ago · Juan Pablo Isaza Relatório

0

use this ans let me know:

 const postSearch = (req, res) => {
     console.log(req.body)   // post if data is received here...
     res.json({
        message: "data received!",
        data: search,        // search should be the data that user fetched
    })
};

On the client side, just console.log the data received and see if it is JSON or not :)))

Happy coding!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda